from flask import Blueprint, request
from utils.ResponseResult import success_json_result, fail_json_result
from models.BookSystemModels import BookTypeModel
from exts import db

bp = Blueprint('book_type_bp', __name__, url_prefix='/type')


@bp.route('/queryBookTypes', methods=['POST'])
def queryBookTypes():
    json_data = request.get_json()
    type_name = json_data.get("typeName", None)
    page_no = json_data.get("pageNo", 1)
    page_size = json_data.get("pageSize", 10)
    isPage = json_data.get("isPage", True)

    query_obj = BookTypeModel.query
    if type_name:
        query_obj = query_obj.filter(BookTypeModel.type_name.like('%' + type_name + '%'))
    # 不分页
    if not isPage:
        data_list = query_obj.all()
        res_json = [
            {
                "typeId": item.type_id,
                "typeName": item.type_name,
                "typeCode": item.type_code
            }
            for item in data_list
        ]
        return success_json_result(data=res_json)
    else:
        paginate_obj = query_obj.paginate(page=page_no, per_page=page_size, error_out=False)
        type_list = paginate_obj.items
        totals = paginate_obj.total
        res_json = [
            {
                "typeId": item.type_id,
                "typeName": item.type_name,
                "typeCode": item.type_code
            }
            for item in type_list
        ]
        result = {
            "bookTypeList": res_json,
            "totals": totals
        }
        return success_json_result(data=result)


@bp.route('/addBookType', methods=['POST'])
def addBookType():
    try:
        db.session.begin()
        json_param = request.get_json()
        print(f"入参：{json_param}")
        type_code = json_param.get("typeCode", None)
        type_name = json_param.get("typeName", None)
        if not type_code or not type_name:
            return fail_json_result(msg="类型编码、名称均不能为空")

        type_info = BookTypeModel(type_code=type_code, type_name=type_name)
        # 保存数据库
        db.session.add(type_info)
        db.session.commit()
        return success_json_result(msg="书籍类型保存成功")
    except Exception as e:
        db.session.rollback()
        return fail_json_result(msg=f"书籍类型保存失败，原因：{e}")


@bp.route('/deleteBookType/<string:typeId>', methods=['GET'])
def deleteBookType(typeId):
    print(f"删除的id：{typeId}")
    type_info = BookTypeModel.query.filter_by(type_id=typeId).first_or_404()
    db.session.delete(type_info)
    db.session.commit()
    return success_json_result(msg="类型删除成功")


@bp.route('/updateBookType', methods=['POST'])
def updateBookType():
    json_param = request.get_json()
    type_id = json_param.get("typeId", None)
    type_name = json_param.get("typeName", None)
    type_code = json_param.get("typeCode", None)
    print(f"入参：{json_param}")
    if not type_id or not type_name or not type_code:
        return fail_json_result(msg="修改参数不能为空")
    try:
        type_info = BookTypeModel.query.get(type_id)
        if not type_info:
            return fail_json_result(msg="书籍类型不存在")
        type_info.type_name = type_name
        type_info.type_code = type_code
        db.session.commit()
        return success_json_result(msg="书籍类型修改成功")
    except Exception as e:
        db.session.rollback()
        return fail_json_result(msg=f"书籍类型修改失败，原因：{e}")
